<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
body, html {
	margin:0;
	padding:0;
}

#plurk {
	height:450px;
	width:300px;
	border:none;
	-webkit-border-radius:3px;
}

.plurk-iframe {
	height:450px;
	width:300px;
	border:none;
	-webkit-border-radius:3px;
}
</style>

<script type="text/javascript" id="iframe_script">
function frameLoaded(){
	var links = document.getElementsByTagName("A");
	for(i=0; i<links.length; i++){
			links[i].addEventListener("click", openURL);
	}

	var forms = document.getElementsByTagName("FORM");
	for(i=0; i<forms.length; i++){
		forms[i].addEventListener("submit", handleSubmit, false);
	}

	var submits = document.getElementsByTagName("INPUT");
	for(i=0; i<submits.length; i++){
		if(submits[i].type=='submit'){
			submits[i].addEventListener('click', 
					function(e){option.name = this.name;}, false);
		}
	}
	
	window.addEventListener("message", messageHandler);

	console.log(target);
	if(target != ""){
		var ele = document.getElementById(target);
		console.log(ele);
		if(ele!=null){
			ele.scrollIntoView(true);
		}
	}
}

function openURL(event){
	var href = event.currentTarget.href;
	parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
	event.preventDefault();
}

function handleSubmit(e){
	console.log(option);
	
	var form = e.srcElement;
	var params = '';
	console.log(form);
	
	for(var i=0; i<form.elements.length;i++){
		var el = form.elements[i];
		if(el.name != undefined) {
			if(el.type == 'checkbox' || el.type == 'radio' ) {
				if(el.checked == true) {
					params += el.name + '=' + el.value + '&';
				}
			}else if(el.type == 'hidden') {
				params += el.name + '=' + el.value + '&';
			}else if(el.nodeName == 'SELECT') {
				params += el.name + '=' + el.value + '&';
			}else if(el.type == 'textarea') {
				params += el.name + '=' + el.value + '&';
			}else if(el.type == 'text') {
				params += el.name + '=' + el.value + '&';
			}else if(el.type == 'password') {
				params += el.name + '=' + el.value + '&';
			}
		}
	}

	if(option.name != ''){
		params += option.name + '=1';
	}
	console.log(params);

	if(form.method == 'post') {		
		parent.postMessage(JSON.stringify({type:'post' , url:form.action, params:params}), "*");
	}else{
		parent.postMessage(JSON.stringify({type:'get' , url:currentUrl, params:params}), "*");
	}
	e.preventDefault();
}

function messageHandler(event){
}

var option = new function(){this.name='';}


</script>
<script type="text/javascript">
var plurkUrl = "http://www.plurk.com/m";
var req;
var currentUrl = "";

function setCurUrl(url) {
	if(url.indexOf("http://www.plurk.com/m/logout")==0){
		currentUrl = plurkUrl;
		localStorage["currentUrl"] = plurkUrl;
	}else{
		localStorage["currentUrl"] = url;
	}
}

function getCurUrl() {
	if(localStorage["currentUrl"] == null){
		return plurkUrl;
	}
	return localStorage["currentUrl"];
}

function main(){
	currentUrl = getCurUrl();
	
	req = new XMLHttpRequest();
	req.onload = handleResponse;
	req.onerror = handleError;
	req.open("GET", currentUrl, true);
	req.send(null);
}

function handleError() {
}

function handleResponse() {
	var doc = req.responseText;
	if(!doc) {
		return;
	}

	if(req.status==200){
		// Succss
		showInFrame(patch(doc));
	}else if(req.status >= 400 && req.status < 500){
		// Client error
		showInFrame(doc);
	}else if(req.status >= 500 && req < 600){
		// Server Error
		showInFrame(doc);
	}

}

function patch(doc) {

	var url = currentUrl.replace(/\?.+/, "")
	                    .replace(/#.+/, "");

	var anchor = "";
	var parts = currentUrl.split("#");
	if(parts.length == 2){
		anchor = parts[1];
	}
	
	return doc.replace(/<\/head>/, 
	          		"<script>" + document.getElementById("iframe_script").textContent +
	          		";var currentUrl=\"" + url + "\"; var target=\"" + anchor + "\";" +
	          		"<" + "/script></head>")
	          .replace(/<body>/, "<body onload='frameLoaded();' style='padding:0px;margin:0px;'>")
	          .replace(/<a href="\/m\/">Plurk<\/a>/, "<a href=\"http://www.plurk.com\">Plurk</a>")
	          .replace(/<a href="\/m/g, "<a href=\"" + plurkUrl)
	          .replace(/href="\?offset/g, "href=\"" + plurkUrl + "?offset")
	          .replace(/href="\?query/g, "href=\"" + plurkUrl + "?query")
	          .replace(/onchange="this\.form\.submit\(\)"/, "onchange=\"var ev=document.createEvent('HTMLEvents'); ev.initEvent('submit', false, true); this.form.dispatchEvent(ev);\"")
	          .replace(/href="#/g, "href=\"" + url + "#");
}

function showInFrame(doc) {					 
	var p = document.getElementById("plurk");
	var f = document.createElement("iframe");
	f.className = "plurk-iframe";
	if(p.firstChild){
		p.removeChild(p.firstChild);
	}
	p.appendChild(f);
	f.src = "data:text/html;charset=utf-8," + doc;
	
	setCurUrl(currentUrl);
}

//---------------------------------------------------------------------
function iframeMessageHandler(e) {
	var iframes = document.getElementsByTagName("IFRAME");
	for(var i=0; i<iframes.length; i++){
		if(iframes[i].contentWindow == e.source){
			var msg = JSON.parse(e.data);
			if(msg){
				if(msg.type=="show"){
					var url = msg.url;
					doGet(url, '');
				}else if(msg.type=="post"){					
					doPost(msg.url, msg.params);
				}else if(msg.type=="get"){
					doGet(msg.url, msg.params);
				}				
			}
			return;
		}
	}
}

function doPost(url, params) {
	if(url == ""){
		url = "http://www.plurk.com/m/";
	}else if(url == "/m/login"){
		url = "http://www.plurk.com/m/login";
	}else if(url.indexOf("/m/p/")==0){
		url = "http://www.plurk.com" + url;	
	}else{
		url = "http://www.plurk.com/m/";
	}

	console.log("post to " + url);
	req.open("POST", url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(params);
}

function doGet(url, params) {
	if(url.indexOf("http:")!=0 && url.indexOf("https:")!=0) {
		return;
	}

	if(url=="http://www.plurk.com/"){ // open regular page 
		chrome.tabs.create({url: "http://www.plurk.com"});
		return;
	}
	
	var link = "";
	if(params != '') {
		link = url + '?' + params;
	}else{
		link = url;
	}

	console.log("try to get " + link);
	if(link.indexOf("http://www.plurk.com")==0){
		// open plurk page in popup window
		// fix redirect
		if(link.indexOf("http://www.plurk.com/m/maar")==0){
			currentUrl = plurkUrl;
		}else if(link.indexOf("http://www.plurk.com/m/p/")==0){
			currentUrl = plurkUrl;
		}else{
			currentUrl = link;
		}
		req.open("GET", link, true);
		req.send(null);
	}else{
		// open other page in new tab
		chrome.tabs.create({url: url, selected:false});
	}
}

window.addEventListener("message", iframeMessageHandler);
</script>
</head>
<body onload="main();">
	<div id="plurk"></div>
</body>
</html>